﻿using System;
using System.Drawing;

namespace CSharpTestProject.Utils
{
    internal class CheckCode
    {
        public static string CreateRandomCode(int codeCount)//制造一个四位的验证码。
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1; Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        //用于生成图的函数
        public static Image CreateImage(string checkCode)//将四位的验证码制作成一张图片
        {
            int iwidth = (int)(checkCode.Length * 16);
            Bitmap image = new Bitmap(iwidth, 20);
            Graphics g = Graphics.FromImage(image);
            Font f = new Font("Arial", 14, FontStyle.Bold);
            Brush b = new SolidBrush(Color.Red);
            g.FillRectangle(new SolidBrush(Color.White), 0, 0, image.Width, image.Height);
            g.Clear(Color.White);
            g.DrawString(checkCode, f, b, 3, 0);
            Pen blackPen = new Pen(Color.YellowGreen, 0);
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                int y = rand.Next(image.Height);
                int x = rand.Next(image.Width);
                g.DrawLine(blackPen, x/2, y/2, x, y);
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            g.Dispose();
            return image;
        }
    
    
    }
}
